package com.heliang.ui.info;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import net.tsz.afinal.annotation.view.ViewInject;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.FrameLayout;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.appxiehui2.R;
import com.heliang.common.FileLog;
import com.heliang.dataaccess.bean.AdvBean;
import com.heliang.dataaccess.bean.InfoBean;
import com.heliang.dataaccess.bean.InfoCatBean;
import com.heliang.dataaccess.bean.MailListBean;
import com.heliang.protocol.requestBean.ReqBodyInfoBean;
import com.heliang.protocol.responseBean.RspBodyInfoBean;
import com.heliang.service.BaseService;
import com.heliang.service.info.impl.IndexServiceImpl;
import com.heliang.service.info.impl.InfoServiceImpl;
import com.heliang.ui.FinalActivityHelper;
import com.heliang.util.Constants;
import com.heliang.util.Encry;
import com.heliang.util.NetDataLoader;
import com.heliang.util.NetDataLoader.DataCallback;
import com.hl.component.LoadingUI;
import com.hl.component.PullToRefreshListView;
import com.hl.component.PullToRefreshListView.OnRefreshListener;
import com.hl.component.exception.ServiceException;

public class IndexActivity extends Activity {
    /**
     * 资讯类别
     */
    @ViewInject(id = R.id.info_cat)
    Gallery info_cat;

    /**
     * 资讯类别左边按钮(绑定事件没有效果)
     */
    @ViewInject(id = R.id.gallery_btn_left, click = "btnOnclick")
    ImageView gallery_btn_left;

    /**
     * 资讯类别右边按钮
     */
    @ViewInject(id = R.id.gallery_btn_right, click = "btnOnclick")
    ImageView gallery_btn_right;

    /**
     * 非首页资讯ListView点击
     */
    @ViewInject(id = R.id.infoCat_news, itemClick = "infoListViewItemClick")
    PullToRefreshListView infoListView;

    /**
     * 首页listView
     */
    @ViewInject(id = R.id.news, itemClick = "infoListViewItemClick")
    ListView indexListView;

    @ViewInject(id = R.id.footer_more, click = "btnOnclick")
    TextView getMoreView;

    private RelativeLayout indexRecomondListRelativeLayout, infocatListRelativeLayout;

    /**
     * 资讯类别
     */
    private List<InfoCatBean> infoCats;

    private List<MailListBean> members;

    private List<AdvBean> advBeans = new ArrayList<AdvBean>();

    private List<InfoBean> infoBeans = new ArrayList<InfoBean>();

    private RelativeLayout indexRecommendRelativelayout;

    private RelativeLayout.LayoutParams pbLP;

    private LoadingUI loadingUI;

    private LayoutInflater layoutInflater;

    private ViewPager viewPager;

    private List<View> dots;

    private TextView advTitle;

    private int currentItem = 0;

    private LinearLayout list_footer;
    
    private LinearLayout footer_loading;
    
    private TextView list_footer_more;
    
    private InfoListAdapter infoAdapter;

    /**
     * 访问网络线程池
     */
    private NetDataLoader netDataLoader;

    private ScheduledExecutorService scheduledExecutorService;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_index);
        new FinalActivityHelper(this).initView();
        // 初始化afinal
        new FinalActivityHelper(this).initView();

        // 初始化数据
        netDataLoader = new NetDataLoader();

        initDate();
    }

    /**
     * 初始化滑动导航
     */
    public void initInfoCat() {
        InfoCatListAdapter infoCatListAdapter = new InfoCatListAdapter(this, infoCats);

        /* 设置一次滑一屏 并选中 */
        int selectIndex;
        int centerIndex = infoCats.size() * 100 / 2;// 取中间值
        int multiple = centerIndex / infoCats.size();// 倍数
        selectIndex = multiple * infoCats.size();// 确定分类选中值
        info_cat.setAdapter(infoCatListAdapter);
        infoCatListAdapter.setSelectedTab(selectIndex);
        info_cat.setSelection(selectIndex);

        /* 为导航设置监听事件 */
        info_cat.setOnItemClickListener(onItemClickListener);

        RelativeLayout layout = (RelativeLayout) findViewById(R.id.info_cat_relativeLayout);
        layout.setVisibility(View.VISIBLE);
    }

    public void initFooterAdv() {
        LayoutInflater inflater = getLayoutInflater();
        View footerView = inflater.inflate(R.layout.index_footer, null);
        indexListView.addFooterView(footerView);
    }

    public void initSerch() {
        LayoutInflater inflater = getLayoutInflater();
        View serchView = inflater.inflate(R.layout.search_bar, null);
        indexListView.addHeaderView(serchView);
    }

    public void initRecomandAdv(List<AdvBean> advBeans) {
        layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View headview = layoutInflater.inflate(R.layout.index_recomand_adv, null);
        FrameLayout framLayout = (FrameLayout) headview.findViewById(R.id.fl_main);
        LayoutParams layoutParams = framLayout.getLayoutParams();
        framLayout.setLayoutParams(layoutParams);

        if (advBeans != null && advBeans.size() != 0) {
            viewPager = (ViewPager) headview.findViewById(R.id.vPager);
            advTitle = (TextView) headview.findViewById(R.id.tv_title);
            dots = new ArrayList<View>();
            dots.add(headview.findViewById(R.id.v_dot0));
            dots.add(headview.findViewById(R.id.v_dot1));
            dots.add(headview.findViewById(R.id.v_dot2));
            dots.add(headview.findViewById(R.id.v_dot3));
            dots.add(headview.findViewById(R.id.v_dot4));

            viewPager.setAdapter(new AdvAdapter(this, advBeans));
            viewPager.setOnPageChangeListener(new PageChangerLister());
        }

        indexListView.addHeaderView(headview);
    }

    /**
     * 换行切换任务
     * @author Administrator
     */
    private class ScrollTask implements Runnable {
        public void run() {
            synchronized (viewPager) {
                currentItem = (currentItem + 1) % advBeans.size();
                handler.obtainMessage().sendToTarget(); // 通过Handler切换图片
            }
        }
    }

    /**
     * 切换当前显示的图片
     */
    private Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            viewPager.setCurrentItem(currentItem);// 切换当前显示的图片
        };
    };

    /**
     * 当viewPage改变时监听事件
     * @author Administrator
     */
    public class PageChangerLister implements OnPageChangeListener {
        private int oldPosition = 0;

        public void onPageScrollStateChanged(int arg0) {
        }

        public void onPageScrolled(int arg0, float arg1, int arg2) {
        }

        public void onPageSelected(int position) {
            currentItem = position;

            String desc = advBeans.get(position).getDec();

            if (desc.length() > 10) {
                desc = desc.substring(0, 12) + "...";
            }

            advTitle.setText(desc);
            dots.get(oldPosition).setBackgroundResource(R.drawable.dot_normal);
            dots.get(position).setBackgroundResource(R.drawable.dot_focused);
            oldPosition = position;
        }
    }

    /**
     * 处理点击事件
     */
    public void btnOnclick(View v) {
        int position;
        switch (v.getId()) {
            case R.id.gallery_btn_left:
                position = info_cat.getSelectedItemPosition();
                info_cat.setSelection(position - 1);
                break;
            case R.id.gallery_btn_right:
                position = info_cat.getSelectedItemPosition();
                info_cat.setSelection(position + 1);
                break;
            case R.id.news:
                Toast.makeText(getApplicationContext(), "news", Toast.LENGTH_SHORT).show();
            default:
                break;
        }
    }

    /**
     * @Description: 资讯列表选中
     * @param: @param arg0
     * @param: @param view
     * @param: @param arg2
     * @param: @param arg3
     * @return: void
     * @throws
     * @author heliang
     * @Date 2013-11-24 上午10:20:44
     */
    public void infoListViewItemClick(AdapterView<?> arg0, View view, int arg2, long arg3) {
        /* 判断是否点击的是加载更多 */
        if (view.equals(list_footer)) {
            this.getMoreInfoNews(infoBeans.get(infoBeans.size() - 1).getCatId(), infoBeans.get(infoBeans.size() - 1).getUpdateTime());
        }

        /* 处理点击资讯 */
        if (view.getTag() == null || !(view.getTag() instanceof InfoBean)) {
            return;
        }

        InfoBean infoBean = (InfoBean) view.getTag();
        Intent intent = new Intent(IndexActivity.this, InfoDetailActivity.class);
        /* 将资讯信息带到资讯详情页面 */
        Bundle bundle = new Bundle();
        bundle.putInt("type", infoBean.getType());
        bundle.putInt("catId", infoBean.getCatId());
        intent.putExtras(bundle);
        intent.putExtra("infoBean", infoBean);

        /* 判断该资讯是否已读 */
        if (!infoBean.isRead() && infoBean instanceof InfoBean) {
            infoBean.setRead(true);
            IndexServiceImpl indexServiceImpl = new IndexServiceImpl(IndexActivity.this);
            try {
                /* 改变文字颜色 */
                TextView titleTv = (TextView) view.findViewById(R.id.recommend_list_item_title_textview);
                TextView descTv = (TextView) view.findViewById(R.id.recommend_list_item_desc_textview);
                titleTv.setTextColor(this.getResources().getColor(R.color.info_list_item_has_read_title));
                descTv.setTextColor(this.getResources().getColor(R.color.info_list_item_has_read_desc));

                /* 更新数据库资讯为已读状态 */
                indexServiceImpl.updateReadStatus(infoBean);
            } catch (ServiceException e) {
                e.printStackTrace();
            }
            startActivityForResult(intent, Constants.HOT_INFO);
        } else {
            IndexActivity.this.startActivityForResult(intent, Constants.HOT_INFO);
        }
    }

    /**
     * @Description:
     * @param: @param infoCatId 类别ID
     * @param: @param lastUpdateTime 最后一次更新时间
     * @return: void
     * @throws
     * @author heliang
     * @Date 2013-11-25 上午9:19:02
     */
    public void getMoreInfoNews(int infoCatId, long lastUpdateTime) {
        final int foot = infoListView.getCount();
        
        /* 改变点击加载更多为加载状态*/
        footer_loading = (LinearLayout) list_footer.findViewById(R.id.footerLoading);
        list_footer_more = (TextView) list_footer.findViewById(R.id.footer_more);
        list_footer_more.setVisibility(View.GONE);
        footer_loading.setVisibility(View.VISIBLE);
       
        InfoServiceImpl infoService = new InfoServiceImpl(this);
        ReqBodyInfoBean reqBodyInfoBean = infoService.getReqBodyInfoBean();
        reqBodyInfoBean.setCatId(infoCatId);
        reqBodyInfoBean.setKeyValue(Encry.md5s(Constants.SITE_ID + Constants.SECKEY));
        reqBodyInfoBean.setSiteId(Constants.SITE_ID);
        reqBodyInfoBean.setUpdateTime(lastUpdateTime);
        reqBodyInfoBean.setVerInfo(-1);
        infoService.setReqBodyInfoBean(reqBodyInfoBean);
        
        DataCallback getMoreCallBack = new DataCallback() {
            @Override
            public void dataLoaded(BaseService baseService) {
                // TODO Auto-generated method stub
                InfoServiceImpl infoService = (InfoServiceImpl)baseService;
                try {
                    RspBodyInfoBean rspBodyInfoBean = infoService.getRspBodyInfoBean();
                    if(rspBodyInfoBean != null && rspBodyInfoBean.getInfoList()!= null){
                        infoBeans.addAll(rspBodyInfoBean.getInfoList());
                        footer_loading.setVisibility(View.GONE);
                        list_footer_more.setVisibility(View.VISIBLE);
                        infoListView.setSelection(foot);
                        infoAdapter.notifyDataSetChanged();
                    } else {
                        footer_loading.setVisibility(View.GONE);
                        list_footer_more.setVisibility(View.VISIBLE);
                        infoListView.removeFooterView(list_footer);
                        Toast.makeText(IndexActivity.this, "没数据了！", Toast.LENGTH_SHORT).show();
                    }
                } catch (Exception e) {
                    // TODO: handle exception
                }
            }
        };
        
        try {
            netDataLoader.loadData(infoService, getMoreCallBack, 1);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 处理资讯分类选中后响应事件
     */
    OnItemClickListener onItemClickListener = new OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            InfoCatListAdapter adapter = (InfoCatListAdapter) parent.getAdapter();
            // 让点击的资讯类别选中
            adapter.setSelectedTab(position);
            InfoCatBean infoCatBean = (InfoCatBean) view.getTag();
            if (infoCatBean != null && infoCatBean instanceof InfoCatBean) {
                changeTab(infoCatBean.getInfoCatId());
            }

        }
    };

    /**
     * @Description: 资讯类别切换
     * @param: @param infoCatId
     * @return: void
     * @throws
     * @author heliang
     * @Date 2013-10-20 上午10:52:30
     */
    public void changeTab(int infoCatId) {
        if (infoCatId != -1) {
            refreshCatInfoList(infoCatId, true, true);
        } else {
            refreshIndexList(true, true);
        }

    }

    /**
     * @Description: 刷新首页资讯列表
     * @param: @param isFirstTime
     * @param: @param needLoading
     * @return: void
     * @throws
     * @author heliang
     * @Date 2013-10-20 上午10:55:44
     */
    private void refreshIndexList(final boolean isFirstTime, boolean needLoading) {

    }

    /**
     * @Description: 刷新非资讯类别信息
     * @param: @param catId 资讯类别ID
     * @param: @param isFirstTime 是否是第一次加载
     * @param: @param needLoading
     * @return: void
     * @throws
     * @author heliang
     * @Date 2013-10-20 上午10:53:36
     */
    private void refreshCatInfoList(final int catId, final boolean isFirstTime, boolean needLoading) {

        /* 让首页推荐资讯排版隐藏 */
        indexRecomondListRelativeLayout.setVisibility(View.GONE);
        infocatListRelativeLayout.setVisibility(View.VISIBLE);

        /* 避免点击过快加载图标重复 */
        if (isFirstTime) {
            indexRecommendRelativelayout.removeView(loadingUI);
            loadingUI = new LoadingUI(this, getResources().getString(R.string.loading_text));
            pbLP = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);

            pbLP.addRule(RelativeLayout.CENTER_IN_PARENT);
            /* 显示异步加载图标 */
            indexRecommendRelativelayout.addView(loadingUI, pbLP);
        }

        /* 异步加载数据并更新UI数据 */
        InfoServiceImpl infoServiceImpl = new InfoServiceImpl(IndexActivity.this);
        infoServiceImpl.getReqBodyInfoBean().setCatId(catId);
        DataCallback dataCallback = new DataCallback() {
            @Override
            public void dataLoaded(BaseService baseService) {
                InfoServiceImpl infoServiceImpl = new InfoServiceImpl(IndexActivity.this);
                infoBeans.clear();
                try {
                    infoBeans = infoServiceImpl.getInfoBeanByCatId(catId, 0);
                    if (infoBeans != null && infoBeans.size() > 0) {
                        infoAdapter = new InfoListAdapter(IndexActivity.this, infoBeans, IndexActivity.this);
                        infoListView.setAdapter(infoAdapter);
                        // 设置下拉刷新事件
                        infoListView.setonRefreshListener(new OnRefreshListener() {
                            @Override
                            public void onRefresh() {
                                refreshCatInfoList(catId, false, false);
                            }
                        });
                        infoAdapter.notifyDataSetChanged();
                        infoListView.setDividerHeight(1);
                    } else {
                        /* 没有数据情况下 */

                    }

                    /* 调用这个方法两种情况：1.第一次加载此类别资讯 2.下拉刷新 */
                    if (isFirstTime) {
                        indexRecommendRelativelayout.removeView(loadingUI);
                    } else {
                        infoListView.onRefreshComplete();
                    }

                    /* 设置底部加载更多按钮 */
                    if (infoListView.getFooterViewsCount() < 1 && infoBeans.size() > 19) {
                        infoListView.addFooterView(list_footer);
                    }
                    if (infoListView.getFooterViewsCount() == 1 && infoBeans.size() < 19) {
                        infoListView.removeFooterView(list_footer);
                    }
                } catch (ServiceException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

                InfoListAdapter infoAdapter = new InfoListAdapter(IndexActivity.this, infoBeans, IndexActivity.this);

                indexRecommendRelativelayout.removeView(loadingUI);
            }
        };

        netDataLoader.loadData(infoServiceImpl, dataCallback, 0);

    }

    /**
     * 初始化数据
     */
    public void initDate() {
        indexRecomondListRelativeLayout = (RelativeLayout) findViewById(R.id.index_recomond_list);
        infocatListRelativeLayout = (RelativeLayout) findViewById(R.id.info_cat_relativeLayout);

        loadingUI = new LoadingUI(this, getResources().getString(R.string.loading_text));
        indexRecommendRelativelayout = (RelativeLayout) findViewById(R.id.index_recommend_relativelayout);

        pbLP = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        pbLP.addRule(RelativeLayout.CENTER_IN_PARENT);

        indexRecommendRelativelayout.addView(loadingUI, pbLP);

        // 构建底部加载更多
        list_footer = (LinearLayout) getLayoutInflater().inflate(R.layout.list_footer, null);

        // 更新完数据后的回调初始化数据
        IndexServiceImpl indexServiceImpl = new IndexServiceImpl(this);
        DataCallback dataCallback = new DataCallback() {
            @Override
            public void dataLoaded(BaseService baseService) {
                IndexServiceImpl indexServiceImpl = (IndexServiceImpl) baseService;
                try {
                    infoCats = indexServiceImpl.getInfoCatList();
                    advBeans = indexServiceImpl.getTopAdvBeanList();
                    infoBeans = indexServiceImpl.getHeadBeanList(1, 0);
                    members = indexServiceImpl.getActiveMember();

                    // 初始化导航
                    initInfoCat();

                    List<InfoBean> infoItemBeanList = new ArrayList<InfoBean>();

                    IndexAdapter indexAdapter = new IndexAdapter(IndexActivity.this, null, infoItemBeanList, members, infoBeans);
                    initSerch();
                    initRecomandAdv(advBeans);
                    initFooterAdv();
                    indexListView.setAdapter(indexAdapter);

                    indexRecommendRelativelayout.removeView(loadingUI);
                } catch (ServiceException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();

                }
            }
        };

        try {
            /* 先更新数据 */
            netDataLoader.loadData(indexServiceImpl, dataCallback, 0);
        } catch (Exception e) {
            e.printStackTrace();
            FileLog.log("IndexActivity.refreshHotList" + e.getMessage());
        }
    }

    @Override
    protected void onStart() {
        scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
        // 当Activity显示出来后，每两秒钟切换一次图片显示
        scheduledExecutorService.scheduleAtFixedRate(new ScrollTask(), 1, 5, TimeUnit.SECONDS);
        super.onStart();
    }

    @Override
    protected void onStop() {
        // 当Activity不可见的时候停止切换
        scheduledExecutorService.shutdown();
        super.onStop();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.index, menu);
        return true;
    }

}
